package com.hd.trans.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;

import com.airbnb.lottie.LottieAnimationView;
import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.common.Constants;
import com.hd.trans.db.bean.HuDunLanguage;
import com.hd.trans.framework.click.XClickUtil;
import com.hd.trans.framework.dialog.ConfirmDialog;
import com.hd.trans.homefun.EventCode;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.network.component.HdTranslateComponent;
import com.hd.trans.network.component.TranslateCallback;
import com.hd.trans.ui.activity.SimulHomeActivity2;
import com.hd.trans.ui.component.HdRecognitionComponent;
import com.hd.trans.ui.component.RecognitionCallBack;
import com.hd.trans.ui.component.RecordFileCallback;
import com.hd.trans.ui.model.SimultaneousModel;
import com.hd.trans.utils.PermissionCallback;
import com.hd.trans.utils.ScreenUtil;
import com.hd.trans.utils.ToastUtils;
import com.hd.trans.utils.TrackerForTrans;
import com.hd.trans.widgets.ImageTextView;
import com.hd.trans.widgets.VoiceLineViewwhite;
import com.hd.trans.widgets.views.floatwindow.apply.OnFloatClickListener;
import com.hd.trans.widgets.views.floatwindow.apply.SimultaneousFloatWindow;
import com.hd.trans.widgets.views.floatwindow.component.ShowType;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public class SimulInterpretFragment2 extends SimulBaseFragment implements View.OnClickListener {
    private SimulHomeActivity2 mActivity;
    private ImageView close;
    private ImageView rotate;
    private RelativeLayout rotateLayout;
    private LinearLayout voiceIcon;
    private TextView beginSpeech;
    private TextView originalText;
    private TextView tvToast;
    private Switch switchView;
    private ImageView ivStartAndStop;
    private ImageView waveLine;
    private ImageTextView radioButton;
    private ImageView btnFloatWindow;
    private LinearLayout fromBt,toBt;
    private ImageView exchange;
    private TextView tvFrom,tvTo;
    private TextView tvTips;
    private TextView tvTips2;

    private Chronometer timeChronometer;
    private VoiceLineViewwhite voiceWaveView;
    private ImageView copyOriginal;
    private TextView translationText;
    private ImageView copyTranslated;
    private HdRecognitionComponent mRecognitionComponent; //语音识别组件
    private HdTranslateComponent mTranslateComponent;  //  文本翻译组件
    public SimultaneousModel mDataModel;
    private ClipboardManager clipMgr;//粘贴板控制
    private NestedScrollView originalScroll;
    private NestedScrollView transScroll;
    private View parentLayout;
    private View bottomLayout;
    private View rlLang;
    private View parsingLayout,parsingLayout2;
    private LottieAnimationView lottie1,lottie2;
    private Handler mHandler;
    private boolean isStarting = true;
    private AnimationDrawable animationDrawable;
    private List<Subsection> subsectionList;
    private Subsection currentSubsection;
    private Subsection lastSubsection;
    private ConfirmDialog dialog;
    private boolean isChecked = false;
    private int showTypeOneCount = 1;
    private int showTypeTwoCount = 0;
    private int screenWidth;
    private boolean isAllowScroll;
    private boolean isAllowSaveRecording;
    private boolean showItFirstTime;
    private boolean isHasNotSaved;
    private SimultaneousFloatWindow simultaneousFloatWindow;
    private boolean isTransCompleted = true;
    private long lastMillisecond;
    private long startTime = 0L;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        TranslationInterior.getTrackerListener().view(TrackerForTrans.TSCY + TrackerForTrans.TRANS_PAGE);
        mActivity = (SimulHomeActivity2) getActivity();
        screenWidth = ScreenUtil.getScreenWidth(mActivity);
        View view = inflater.inflate(R.layout.fragment_simul_interpret2, container, false);
        initView(view);
        setThemeColor();//给改变换颜色的控件换颜色
        return view;
    }


    private void initView(View view) {
        mHandler = new Handler();
        currentSubsection = new Subsection();
        lastSubsection = new Subsection();
        subsectionList = new ArrayList<>();
        subsectionList.add(currentSubsection);
        close = view.findViewById(R.id.close);
        rotate = view.findViewById(R.id.ic_rotate);
        rotateLayout = view.findViewById(R.id.rotate_layout);
        voiceIcon = view.findViewById(R.id.voice_icon);
        beginSpeech = view.findViewById(R.id.begin_speech);
        originalText = view.findViewById(R.id.original_text);
        timeChronometer = view.findViewById(R.id.time_chronometer);
        voiceWaveView = view.findViewById(R.id.voiceWaveView);
        copyOriginal = view.findViewById(R.id.copy_original);
        translationText = view.findViewById(R.id.translation);
        copyTranslated = view.findViewById(R.id.copy_translated);
        originalScroll = view.findViewById(R.id.original_scroll);
        transScroll = view.findViewById(R.id.trans_scroll);
        parentLayout = view.findViewById(R.id.root_view);
        parsingLayout = view.findViewById(R.id.parsing_layout);
        parsingLayout2 = view.findViewById(R.id.parsing_layout2);
        tvToast = view.findViewById(R.id.tv_toast);
        switchView = view.findViewById(R.id.switch_view);
        lottie1 = view.findViewById(R.id.lottie1);
        lottie2 = view.findViewById(R.id.lottie2);
        bottomLayout = view.findViewById(R.id.bottom_layout);
        ivStartAndStop = view.findViewById(R.id.iv_start_and_stop);
        waveLine = view.findViewById(R.id.wave_line);
        radioButton = view.findViewById(R.id.radio_button);
        btnFloatWindow = view.findViewById(R.id.btn_float_window);
        fromBt = view.findViewById(R.id.left_bt);
        toBt = view.findViewById(R.id.right_bt);
        exchange = view.findViewById(R.id.icon_exchange);
        tvFrom = view.findViewById(R.id.tv_from);
        tvTo = view.findViewById(R.id.tv_to);
        tvTips = view.findViewById(R.id.tv_tips);
        tvTips2 = view.findViewById(R.id.tv_tips2);
        rlLang = view.findViewById(R.id.rl_lang);
        rlLang.setVisibility(View.GONE);//初始化隐藏
        isAllowSaveRecording = PreferenceMgr.getInstance().isAllowSaveChecked();
        radioButton.setSelected(isAllowSaveRecording);
        animationDrawable = (AnimationDrawable) waveLine.getBackground();
        //开始
        animationDrawable.start();

        btnFloatWindow.setVisibility(SimulHomeActivity2.isOpenFloatWindow ? View.VISIBLE : View.GONE);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActivity.onBackPressed();
            }
        });
        switchView.setOnCheckedChangeListener((buttonView, isChecked) -> {
            //两个埋点
            TranslationInterior.getTrackerListener().click(
                    TrackerForTrans.TSCY,
                    isChecked?TrackerForTrans.COLUMNS_SHOW:TrackerForTrans.MERGE_SHOW,
                    TrackerForTrans.SHOW
            );
            TranslationInterior.getTrackerListener().click(
                    TrackerForTrans.TSCY,
                    TrackerForTrans.SWITCH_BUTTON
            );
            setShowLottieAnimation(isChecked);
        });
        rotate.setOnClickListener(this);
        copyOriginal.setOnClickListener(this);
        copyTranslated.setOnClickListener(this);
        ivStartAndStop.setOnClickListener(this);
        fromBt.setOnClickListener(this);
        toBt.setOnClickListener(this);
        exchange.setOnClickListener(this);
        radioButton.setOnClickListener(this);
        radioButton.setOnClickListener(this);
        btnFloatWindow.setOnClickListener(this);

        updateButton(1);
        showTips2();
    }

    public void stopRecording(){
        if(isStarting){
            ivStartAndStop.performClick();
        }
    }

    public void stopOrDestroy(){
        if(mRecognitionComponent != null)
            mRecognitionComponent.stopRecognition();
        if(mTranslateComponent != null)
            mTranslateComponent.destroy();
    }

    private float downX,downY,upX,upY,lastTempY,downWeight;
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if(action == MotionEvent.ACTION_DOWN){
            downX = event.getX();
            downY = event.getY();
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bottomLayout.getLayoutParams();
            downWeight = params.weight;

            isAllowScroll = downX > screenWidth*2/3;
        }else if(action == MotionEvent.ACTION_UP){
            if(isAllowScroll){
                upX = event.getX();
                upY = event.getY();
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bottomLayout.getLayoutParams();
                if(params.weight > 0.5f){
                    if(switchView.isChecked()){
                        mHandler.removeCallbacks(hideBottomAnimation);
                        mHandler.removeCallbacks(showBottomAnimation);
                        mHandler.post(showBottomAnimation);
                    }else {
                        switchView.setChecked(true);
                    }

                }else {
                    if(switchView.isChecked()){
                        switchView.setChecked(false);
                    }else {
                        mHandler.removeCallbacks(hideBottomAnimation);
                        mHandler.removeCallbacks(showBottomAnimation);
                        mHandler.post(hideBottomAnimation);
                    }
                }
            }

        }else if(action == MotionEvent.ACTION_MOVE){
            if(isAllowScroll){
                float currentX = event.getX();
                float currentY = event.getY();
                float tempY = downY - currentY;
                if(lastTempY != tempY){
                    lastTempY = tempY;
                    float d = (downY - currentY)/10.0f * 0.01f;
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bottomLayout.getLayoutParams();
                    params.weight = downWeight+d;
                    if(params.weight > 1){
                        params.weight = 1.0f;
                        bottomLayout.setLayoutParams(params);
                    }else if(params.weight<=1 && params.weight> 0){
                        bottomLayout.setLayoutParams(params);
                    }else {
                        params.weight = 0f;
                        bottomLayout.setLayoutParams(params);
                    }
                    bottomLayout.invalidate();
                }
            }

        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onBackPressed() {
        if(isStarting){
            ivStartAndStop.performClick();
            return true;
        }
        if(isAllowSaveRecording){
            if(isHasNotSaved){
                return showExitDialog();
            }
        }else {
            return showExitDialog();
        }
        finishFragment();
        return true;
    }

    private boolean showExitDialog(){
        if(!PreferenceMgr.getInstance().isNeverShowThisTips()
                &&!TextUtils.isEmpty(originalText.getText().toString().trim())){
            if (dialog == null) {
                dialog = ConfirmDialog.builder()
                        .setContent(getResources().getString(R.string.confirm_tip3))
                        .rightTxt(getResources().getString(R.string.str_keep_out))
                        .setShowCheckBox(true)
                        .setChecked(isChecked)
                        .setOnCheckedChangeListener((buttonView, isChecked) -> {
                            this.isChecked = isChecked;
                        })
                        .setRightListenner(dialog ->{
                            PreferenceMgr.getInstance().setNeverShowThisTips(isChecked);
                            finishFragment();
                        })
                        .setLeftListenner(dialog -> {
                            PreferenceMgr.getInstance().setNeverShowThisTips(isChecked);
                        })
                        .build();
            }
            dialog.show(getActivity().getSupportFragmentManager(), "SimulHomeActivity");

            return true;
        }

        return false;
    }

    private void finishFragment(){
        stopOrDestroy();
        if(mActivity.isTopStyle){
            mActivity.finish();
        }else {
            mActivity.getSupportFragmentManager().popBackStack();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopOrDestroy();
        getLifecycle().removeObserver(mRecognitionComponent);
        getLifecycle().removeObserver(mTranslateComponent);
        //如果是处于需要计时的状态

        if(mHandler != null){
            mHandler.post(hideToastRunnable);
        }

        if(simultaneousFloatWindow != null){
            simultaneousFloatWindow.remove();
        }

        mDataModel.getLanguageFrom().removeObservers(this);
        mDataModel.getLanguageTo().removeObservers(this);
    }

    @Override
    void onlazyLoad() {
        mDataModel = mActivity.mDataModel;

        mRecognitionComponent = new HdRecognitionComponent(mActivity,false, new RecordFileCallback() {
            private String taskId;

            @Override
            public void createRecordFile(String taskId) {
                if(isAllowSaveRecording){
                    this.taskId = taskId;
                    TranslationInterior.getRecordFileCallback().createRecordFile(taskId);
                }
            }

            @Override
            public void writeByteToFile(byte[] bytes) {
                if(isAllowSaveRecording){
                    TranslationInterior.getRecordFileCallback().writeByteToFile(bytes);
                }
            }

            @Override
            public void savePcmToWav(String taskId) {
                if(isAllowSaveRecording){
                    if(lastSubsection != null && !TextUtils.isEmpty(lastSubsection.originalContent)){
                        mHandler.post(() -> ToastUtils.showNormal("录音文件保存成功！\n请在历史记录中查看！"));
                        TranslationInterior.getRecordFileCallback().savePcmToWav(taskId);
                        TranslationInterior.getRecordFileCallback().saveRecord(
                                taskId,
                                mDataModel.getLanguageFrom().getValue().getTranslateCode(),
                                mDataModel.getLanguageTo().getValue().getTranslateCode(),
                                lastSubsection.originalContent,
                                lastSubsection.translateContent
                        );
                        lastSubsection.setOriginalContent("");
                        lastSubsection.setTranslateContent("");
                    }
                }else {
                    isHasNotSaved = true;
                }
            }

            @Override
            public void saveRecord(String taskId, String origCode, String transCode, String origContent, String transContent) {
                if(isAllowSaveRecording){
                    //
                }
            }
        });
        getLifecycle().addObserver(mRecognitionComponent);

        mTranslateComponent = new HdTranslateComponent(getActivity());
        getLifecycle().addObserver(mTranslateComponent);

        clipMgr = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
        executeRecognize(false);

        mDataModel.getLanguageFrom().observe(this, huDunLanguage -> {
            if (huDunLanguage != null) {
                toTalkingTips(isStarting);
                tvFrom.setText(huDunLanguage.getName());
            }
        });
        mDataModel.getLanguageTo().observe(this, huDunLanguage -> {
            if (huDunLanguage != null) {
                tvTo.setText(huDunLanguage.getName());
            }
        });
    }

    private void toTalkingTips(boolean isStarting) {
        if ("英语".equals(mDataModel.getLanguageFrom().getValue().getName())) {
            if(isStarting){
                beginSpeech.setText("Please start talking");
            }else {
                beginSpeech.setText("Click the button at the bottom left to start talking");
            }
        } else {
            if(isStarting){
                beginSpeech.setText("请开始说话吧");
            }else {
                beginSpeech.setText("点击左下方按键后开始说话");
            }
        }
    }

    @Override
    void onDataFresh() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if(simultaneousFloatWindow != null){
            simultaneousFloatWindow.hidden();
        }
    }


    /**
     * 语音识别
     * isReverse 是否为逆向翻译
     */
    private void executeRecognize(boolean isReverse) {
        mHandler.postDelayed(showToastRunnable, 5000);
        mHandler.post(showTipsRunnable);
        isSucceed = false;
        timeChronometer.setBase(SystemClock.elapsedRealtime());
        timeChronometer.start();
        startTime = System.currentTimeMillis();
        mRecognitionComponent.voiceRecognition(mDataModel.getLanguageFrom().getValue(), new RecognitionCallBack() {
            @Override
            public void onRecognitionFailed(String msg, int code) {
                stopRecording();
                mHandler.post(hideToastRunnable);
                Toast.makeText(mActivity, R.string.voice_service_busy, Toast.LENGTH_SHORT).show();
                startTime = 0;
            }

            @Override
            public void onRecognitionCompleted(String msg, int code) {
                //根据翻译是否有成功，保存使用掉的时间。
                if(startTime > 0){
                    mActivity.saveUseTime(System.currentTimeMillis() - startTime);
                    startTime = 0;
                }
            }

            @Override
            public void onRecognitionChanged(String msg, int code, boolean sentenceOver, String sentence) {
                if(TextUtils.isEmpty(sentence.trim())) return;
                updateFloatWindow();
                changeOriginalText(msg);
                if (sentenceOver) {
                    executeTranslate(sentence, new TranslateCallback() {
                        @Override
                        public void onTranslateFailed(int code, String msg) {
                            isTransCompleted = true;
                            if(code == Constants.ResponseCode.ERROR_IS_DANGER
                                    || code == Constants.ResponseCode.ERROR_COMM){
                                ToastUtils.showError(msg);
                            }else {
                                ToastUtils.showError(R.string.fanyi_faith_tip);
                            }
                        }

                        @Override
                        public void onTranslateCompleted(
                                String data,
                                String fromLangCode,
                                String toLangCode,
                                boolean status) {
                            isTransCompleted = true;
                            isSucceed = true;
                            if(currentSubsection != null){
                                final String originalContent = sentence;
                                final String translateContent = data.replace("\n","");
                                currentSubsection.setOriginalContent(originalContent);
                                currentSubsection.setTranslateContent(translateContent);

                                lastSubsection.setOriginalContent(lastSubsection.originalContent + sentence);
                                lastSubsection.setTranslateContent(lastSubsection.translateContent + data.replace("\n", ""));

                                updateFloatWindow();

                            }
                            //分段：保存段落，新段落
                            saveSection();

                            changeOriginalText("");
                            changeTranslationText();
                        }
                    });
                }else{
                    if(isTransCompleted && sentence.length() >= 3 && sentence.length() < 100){
                        long currentMillisecond = System.currentTimeMillis();
                        //预翻译，间隔3000毫秒
                        if((currentMillisecond - lastMillisecond) > 3000){
                            lastMillisecond = currentMillisecond;
                            executeTranslate(sentence, new TranslateCallback() {
                                @Override
                                public void onTranslateFailed(int code, String msg) {
                                    isTransCompleted = true;
                                    if(code == Constants.ResponseCode.ERROR_IS_DANGER
                                            || code == Constants.ResponseCode.ERROR_COMM){
                                        ToastUtils.showError(msg);
                                    }else {
                                        ToastUtils.showError(R.string.fanyi_faith_tip);
                                    }
                                }

                                @Override
                                public void onTranslateCompleted(
                                        String data,
                                        String fromLangCode,
                                        String toLangCode,
                                        boolean status) {
                                    isTransCompleted = true;
                                    isSucceed = true;
                                    if(currentSubsection != null){
                                        final String originalContent = sentence;
                                        final String translateContent = data.replace("\n","");
                                        currentSubsection.setOriginalContent(originalContent);
                                        currentSubsection.setTranslateContent(translateContent);

                                        updateFloatWindow();

                                    }
                                    changeOriginalText("");
                                    changeTranslationText();
                                }
                            });
                        }
                    }
                }
                voiceIcon.setVisibility(View.GONE);
                originalScroll.postDelayed(() -> originalScroll.fullScroll(View.FOCUS_DOWN), 10);
                transScroll.postDelayed(() -> transScroll.fullScroll(View.FOCUS_DOWN), 10);
                mHandler.post(hideToastRunnable);
            }

            @Override
            public void onVoiceChanged(int waveBytes, int readBytes) {
                /*double dB = 10 * Math.log10(waveBytes / (double) readBytes);
                voiceWaveView.setVolume((int) (dB));*/
            }
        });
    }

    private void updateFloatWindow() {
        if(simultaneousFloatWindow != null){
            simultaneousFloatWindow.changeContent(currentSubsection.originalContent, currentSubsection.translateContent);
        }
    }

    private void saveSection() {
        if(currentSubsection == null)return;
        //分段：保存段落
        try {
            Subsection subsection = currentSubsection.clone();
            if(!TextUtils.isEmpty(subsection.getOriginalContent())
                    || !TextUtils.isEmpty(subsection.getTranslateContent())){
                subsectionList.add(subsectionList.size()-1,subsection);
                recordContent();
                currentSubsection.setOriginalContent("");
                currentSubsection.setTranslateContent("");
            }
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    private Runnable showToastRunnable = new Runnable() {
        @Override
        public void run() {
            if(voiceIcon.getVisibility() == View.VISIBLE || isStarting){
                mHandler.removeCallbacks(hideToastRunnable);
                tvToast.setVisibility(View.VISIBLE);
            }
        }
    };

    private Runnable hideToastRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.removeCallbacks(showToastRunnable);
            tvToast.setVisibility(View.GONE);
        }
    };

    private Runnable showTipsRunnable = new Runnable() {
        @Override
        public void run() {
            if(isStarting){
                showTypeOneCount ++;
                if(showTypeOneCount>2){
                    mHandler.removeCallbacks(hideTipsRunnable);
                    tvTips.setVisibility(View.GONE);
                    return;
                }
            }else {
                showTypeTwoCount ++;
                if(showTypeTwoCount>1){
                    mHandler.removeCallbacks(hideTipsRunnable);
                    tvTips.setVisibility(View.GONE);
                    return;
                }
            }

            String tips = "";
            if(isAllowSaveRecording){
                tips = mActivity.getResources().getString(isStarting?R.string.record_stop2:R.string.record_start);
            }else {
                tips = mActivity.getResources().getString(isStarting?R.string.record_stop:R.string.record_start);
            }

            tvTips.setText(tips);

            tvTips.setVisibility(View.VISIBLE);
            tvToast.setVisibility(View.GONE);

            mHandler.removeCallbacks(hideTipsRunnable);
            mHandler.postDelayed(hideTipsRunnable,5000);
        }
    };

    private Runnable hideTipsRunnable = new Runnable() {
        @Override
        public void run() {
            tvTips.setVisibility(View.GONE);
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }


    //记录是否翻译成功
    private boolean isSucceed;

    /**
     * 执行翻译
     */
    private void executeTranslate(String sentence, TranslateCallback callback) {
        if (TextUtils.isEmpty(sentence)) return;
        if(mDataModel.getLanguageTo().getValue() == null
                || mDataModel.getLanguageFrom().getValue() == null){
            return;
        }
        String fromTranslateCode = mDataModel.getLanguageFrom().getValue().getTranslateCode();
        String toTranslateCode = mDataModel.getLanguageTo().getValue().getTranslateCode();

        isTransCompleted = false;
        mTranslateComponent.translationText(
                mActivity,
                sentence,
                fromTranslateCode,
                toTranslateCode,
                PreferenceMgr.getInstance().isOpenOfflineTrans(),
                callback);
    }

    StringBuilder originalOriginalTextMe = new StringBuilder();
    StringBuilder originalOriginalTextSp = new StringBuilder();
    private void recordContent() {
        final StringBuilder originalOriginalTextMe = new StringBuilder();
        final StringBuilder originalOriginalTextSp = new StringBuilder();
        if(subsectionList.size() > 1){
            for (int i=0;i<subsectionList.size()-1;i++){
                Subsection subsection = subsectionList.get(i);
                originalOriginalTextSp.append(subsection.originalContent);
                originalOriginalTextSp.append("\n\n");

                originalOriginalTextMe.append(subsection.originalContent);
                originalOriginalTextMe.append("\n");
                originalOriginalTextMe.append(subsection.translateContent);
                originalOriginalTextMe.append("\n\n");
            }
        }
        this.originalOriginalTextMe = originalOriginalTextMe;
        this.originalOriginalTextSp = originalOriginalTextSp;
    }

    private void changeOriginalText(String msg) {
        StringBuilder originalTextBuilder = new StringBuilder();
        Subsection subsection = subsectionList.get(subsectionList.size()-1);
        if(switchView.isChecked()){
            originalTextBuilder.append(originalOriginalTextSp);
            originalTextBuilder.append(subsection.originalContent);
            originalTextBuilder.append(msg);
        }else {
            originalTextBuilder.append(originalOriginalTextMe);
            originalTextBuilder.append(subsection.originalContent);
            originalTextBuilder.append(msg);
            originalTextBuilder.append("\n");
            originalTextBuilder.append(subsection.translateContent);
        }
        originalTextBuilder.append("\n\n");
        String result = originalTextBuilder.toString();
        if(TextUtils.isEmpty(result.trim()))return;
        originalText.setText(result);
    }

    private void changeTranslationText() {
        StringBuilder translationTextBuilder = new StringBuilder();
        for (Subsection subsection:subsectionList){
            translationTextBuilder.append(subsection.translateContent);
            translationTextBuilder.append("\n\n");
        }
        String result = translationTextBuilder.toString();
        if(TextUtils.isEmpty(result.trim()))return;
        translationText.setText(result);
    }


    private boolean isRotate;

    @Override
    public void onClick(View v) {
        if(XClickUtil.isFastDoubleClick(v,XClickUtil.INTERVAL_MILLIS)){
            return;
        }
        hideTips2();//有其它操作，隐藏提示
        int id = v.getId();
        if (id == R.id.ic_rotate) {
            if (mActivity.isLimit4Use(EventCode.SIMUL_ROTATE_TRANSLATED)) {
                if (!isRotate) {
                    rotateLayout.setRotationX(180);
                    rotateLayout.setRotationY(180);
                } else {
                    rotateLayout.setRotationX(360);
                    rotateLayout.setRotationY(360);
                }
                isRotate = !isRotate;
            }
        } else if (id == R.id.copy_original) {
            if (mActivity.isLimit4Use(EventCode.SIMUL_COPY_ORIGINAL)) {
                if (!TextUtils.isEmpty(originalText.getText())) {
                    //埋点
                    TranslationInterior.getTrackerListener().click(
                            TrackerForTrans.TSCY,
                            switchView.isChecked()?TrackerForTrans.COPY_ORIGINAL_CONTENT:TrackerForTrans.COPY_MERGE_CONTENT
                    );
                    ClipData mClipData = ClipData.newPlainText("Label", originalText.getText());
                    clipMgr.setPrimaryClip(mClipData);
                    Toast.makeText(mActivity, "文字已复制", Toast.LENGTH_SHORT).show();
                }
            }
        } else if (id == R.id.copy_translated) {
            if (mActivity.isLimit4Use(EventCode.SIMUL_COPY_TRANSLATED)) {
                if (!TextUtils.isEmpty(translationText.getText())) {
                    //埋点
                    TranslationInterior.getTrackerListener().click(
                            TrackerForTrans.TSCY,
                            TrackerForTrans.COPY_TRANS_CONTENT
                    );
                    ClipData mClipData = ClipData.newPlainText("Label", translationText.getText());
                    clipMgr.setPrimaryClip(mClipData);
                    Toast.makeText(mActivity, "文字已复制", Toast.LENGTH_SHORT).show();
                }
            }
        } else if (id == R.id.iv_start_and_stop) {
            //埋点
            TranslationInterior.getTrackerListener().click(
                    TrackerForTrans.TSCY,
                    isStarting?TrackerForTrans.RECORD_STOP:TrackerForTrans.RECORD_START,
                    TrackerForTrans.RECORD
            );

            if (!mActivity.isLimit4Use(EventCode.SIMUL_TRANSLATE)) {
                return;
            }

            Drawable drawable = ivStartAndStop.getDrawable();
            if(isStarting){//暂停
                showTips2();
                isStarting = false;
                toTalkingTips(false);
                drawable.setLevel(2);

                if(mRecognitionComponent != null)
                    mRecognitionComponent.stopRecognition();
                timeChronometer.stop();
                animationDrawable.stop();
                waveLine.setBackgroundResource(R.drawable.ic_line);
                mHandler.post(hideToastRunnable);
                rlLang.setVisibility(View.VISIBLE);

                showLottieAnimation1(false);
                showLottieAnimation2(false);
                radioButton.setAlpha(1.0f);
            }else {//恢复播放
                isStarting = true;
                toTalkingTips(true);
                drawable.setLevel(1);

                executeRecognize(false);
                waveLine.setBackground(animationDrawable);
                animationDrawable.start();
                rlLang.setVisibility(View.GONE);

                showLottieAnimation1(switchView.isChecked());
                showLottieAnimation2(!switchView.isChecked());
                radioButton.setAlpha(0.5f);
            }
            mHandler.removeCallbacks(showTipsRunnable);
            mHandler.post(showTipsRunnable);
            ivStartAndStop.setImageDrawable(drawable);
        }else if (id == R.id.left_bt) {
            mActivity.showLanguageDialog(true);
        } else if (id == R.id.right_bt) {
            mActivity.showLanguageDialog(false);
        } else if (id == R.id.icon_exchange) {
            showTranslateAnimation();
        } else if (id == R.id.radio_button) {
            if(radioButton.getAlpha() == 1f){
                isAllowSaveRecording = !isAllowSaveRecording;
                radioButton.setSelected(isAllowSaveRecording);
                updateButton(2);
            }else {
                ToastUtils.showNormal("录音中无法修改设置");
            }
        } else if (id == R.id.btn_float_window) {
            //埋点
            TranslationInterior.getTrackerListener().click(
                    TrackerForTrans.TSCY,
                    "开启字幕浮窗"
            );

            String[] permissions6 = new String[]{
                    Manifest.permission.SYSTEM_ALERT_WINDOW,
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION};
            mActivity.checkPermissionAndStart(permissions6,new PermissionCallback() {
                @Override
                public void doNext() {
                    if(simultaneousFloatWindow == null){
                        simultaneousFloatWindow = new SimultaneousFloatWindow(
                                mActivity,
                                mActivity.getPackageName(),
                                new OnFloatClickListener() {
                                    @Override
                                    public void showType(@Nullable View view, @NonNull ShowType type) {
                                        //埋点
                                        TranslationInterior.getTrackerListener().click(
                                                "字幕浮窗",
                                                "显示模式"
                                        );
                                    }

                                    @Override
                                    public void setting(@Nullable View view) {
                                        //埋点
                                        TranslationInterior.getTrackerListener().click(
                                                "字幕浮窗",
                                                "设置"
                                        );
                                    }

                                    @Override
                                    public void screenRecover(@Nullable View view) {
                                        //埋点
                                        TranslationInterior.getTrackerListener().click(
                                                "字幕浮窗",
                                                "跳转到同声传译"
                                        );
                                    }

                                    @Override
                                    public void closeFloatWindow(@Nullable View view) {
                                        //埋点
                                        TranslationInterior.getTrackerListener().click(
                                                "字幕浮窗",
                                                "关闭浮窗"
                                        );
                                        if(isStarting){
                                            ivStartAndStop.performClick();
                                        }
                                    }
                                });
                    }

                    //显示
                    simultaneousFloatWindow.changeLang(
                            mDataModel.getLanguageFrom().getValue().getName(),
                            mDataModel.getLanguageTo().getValue().getName());
                    simultaneousFloatWindow.show();
                    if(!isStarting){
                        ivStartAndStop.performClick();
                    }
                }
            });
        }
    }

    private void showTips2() {
        if(!isAllowSaveRecording && !showItFirstTime){
            showItFirstTime = true;
            tvTips2.setVisibility(View.VISIBLE);
        }
    }
    private void hideTips2() {
        tvTips2.setVisibility(View.GONE);
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void updateButton(int level){
        if(isAllowSaveRecording){
            ivStartAndStop.setImageResource(R.drawable.ic_stop_and_start_red);
        }else {
            ivStartAndStop.setImageResource(R.drawable.ic_stop_and_start);
        }
        Drawable drawable = ivStartAndStop.getDrawable();
        drawable.setLevel(level);
        ivStartAndStop.setImageDrawable(drawable);
    }

    /**
     * 互换语种动画
     */
    private void showTranslateAnimation() {
        if("自动检测".equals(mDataModel.getLanguageFrom().getValue().getName())){
            ToastUtils.showNormal(getResources().getString(R.string.tips_to_not_auto));
            return;
        }
        TranslateAnimation ta1 = new TranslateAnimation(0, fromBt.getWidth() + exchange.getWidth(), 0, 0);
        ta1.setDuration(600);
        ta1.setFillAfter(true);
        fromBt.startAnimation(ta1);
        fromBt.bringToFront();

        TranslateAnimation ta2 = new TranslateAnimation(0, -toBt.getWidth()-exchange.getWidth(), 0, 0);
        ta2.setDuration(600);
        ta2.setFillAfter(true);
        toBt.startAnimation(ta2);
        toBt.bringToFront();

        ta1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                HuDunLanguage fromTemp = mDataModel.getLanguageFrom().getValue();
                mDataModel.setLanguageFrom(mDataModel.getLanguageTo().getValue());
                mDataModel.setLanguageTo(fromTemp);
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        ta2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    //设置颜色
    private void setThemeColor() {
        parentLayout.setBackgroundColor(TranslationInterior.getThemeColor());
        copyOriginal.setImageTintList(ColorStateList.valueOf(Color.parseColor("#C0C4CC")));
        copyTranslated.setImageTintList(ColorStateList.valueOf(Color.parseColor("#C0C4CC")));
        translationText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s.toString().trim())) {
                    copyTranslated.setEnabled(false);
                    parsingLayout.setVisibility(View.VISIBLE);
                    copyTranslated.setImageTintList(ColorStateList.valueOf(Color.parseColor("#C0C4CC")));
                } else {
                    parsingLayout.setVisibility(View.GONE);
                    copyTranslated.setEnabled(true);
                    copyTranslated.setImageTintList(ColorStateList.valueOf(TranslationInterior.getThemeColor()));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        originalText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s.toString().trim())) {
                    parsingLayout2.setVisibility(View.VISIBLE);
                    copyOriginal.setEnabled(false);
                    copyOriginal.setImageTintList(ColorStateList.valueOf(Color.parseColor("#C0C4CC")));
                } else {
                    parsingLayout2.setVisibility(View.GONE);
                    copyOriginal.setEnabled(true);
                    copyOriginal.setImageTintList(ColorStateList.valueOf(Color.parseColor("#ffffff")));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void setShowLottieAnimation(boolean isChecked){
        //Lottie动画
        showLottieAnimation1(isChecked);
        showLottieAnimation2(!isChecked);

        //内容窗口动画
        if(isChecked){
            mHandler.removeCallbacks(hideBottomAnimation);
            mHandler.removeCallbacks(showBottomAnimation);
            mHandler.post(showBottomAnimation);
        }else {
            //埋点
            TranslationInterior.getTrackerListener().view(TrackerForTrans.VIEW_MERGE_SHOW);
            mHandler.removeCallbacks(hideBottomAnimation);
            mHandler.removeCallbacks(showBottomAnimation);
            mHandler.post(hideBottomAnimation);
        }
        changeOriginalText("");

        //文本框滑动到底部内容
        originalScroll.postDelayed(() -> originalScroll.fullScroll(View.FOCUS_DOWN), 200);
        transScroll.postDelayed(() -> transScroll.fullScroll(View.FOCUS_DOWN), 200);
    }

    private Runnable showBottomAnimation = new Runnable() {

        @Override
        public void run() {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bottomLayout.getLayoutParams();
            if(params.weight<1){
                params.weight += 0.05f;
                bottomLayout.setLayoutParams(params);
                mHandler.postDelayed(this,5);
            }else {
                params.weight = 1.0f;
                bottomLayout.setLayoutParams(params);
            }
            bottomLayout.invalidate();
        }
    };
    private Runnable hideBottomAnimation = new Runnable() {

        @Override
        public void run() {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bottomLayout.getLayoutParams();
            if(params.weight<=1 && params.weight> 0){
                params.weight -= 0.05f;
                bottomLayout.setLayoutParams(params);
                mHandler.postDelayed(this,5);
            }else {
                params.weight = 0f;
                bottomLayout.setLayoutParams(params);
            }
            bottomLayout.invalidate();
        }
    };

    private void showLottieAnimation1(boolean allowShow) {
        if(allowShow && isStarting && TextUtils.isEmpty(translationText.getText().toString().trim())){
            parsingLayout.setVisibility(View.VISIBLE);
            lottie1.playAnimation();
        }else {
            parsingLayout.setVisibility(View.GONE);
            lottie1.pauseAnimation();
        }

    }

    private void showLottieAnimation2(boolean allowShow) {
        if(allowShow && isStarting && TextUtils.isEmpty(originalText.getText().toString().trim())){
            parsingLayout2.setVisibility(View.VISIBLE);
            lottie2.playAnimation();
        }else {
            parsingLayout2.setVisibility(View.GONE);
            lottie2.pauseAnimation();
        }
    }

    private class Subsection implements Cloneable {
        private String originalContent = "";
        private String translateContent = "";

        public String getOriginalContent() {
            return originalContent;
        }

        public void setOriginalContent(String originalContent) {
            this.originalContent = originalContent;
        }

        public String getTranslateContent() {
            return translateContent;
        }

        public void setTranslateContent(String translateContent) {
            this.translateContent = translateContent;
        }

        @NonNull
        @NotNull
        @Override
        protected Subsection clone() throws CloneNotSupportedException {
            return (Subsection) super.clone();
        }
    }
}
